package com.itheima.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itheima.anno.Log;
import com.itheima.mapper.DeptLogMapper;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.pojo.OperateLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    //注入Mapper接口
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;

    private OperateLogMapper operateLogMapper;

    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    @Transactional(rollbackFor = Exception.class)  //spring事务管理     事务：事务是一组操作的集合，它是一个不可分割的工作单位，这些操作要么同时成功，要么同时失败
                    // rollbackFor,默认情况下，只有出现RuntimeException才回滚异常。rollbackFor属性用于控制出现何种异常类型，回滚事务。
    @Override
    public void delete(Integer id) {

        try {
            deptMapper.deleteById(id);  //根据ID删除部门数据

//            int i = 1/0;

            empMapper.deleteByDeptId(id);   //根据部门id删除该部门下的员工
        } finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门操作，此次解散的是"+id+"号部门");
            deptLogService.insert(deptLog); //记录操作日志
        }


    }


    @Override
    public void add(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    @Override
    public Dept query(Integer id) {

        return deptMapper.selectById(id);
    }


    @Override
    public void alter(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
